package com.loong.web.gp4j.service.statistic;

import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.loong.tool.lang.Dates;
import com.loong.web.gp4j.bean.vo.statistic.EnvVo;
import com.loong.web.gp4j.bean.vo.util.CountVo;
import com.loong.web.gp4j.dao.statistic.StatisticDao;
import com.loong.web.suppert.collection.vo.ResultVo;
import com.loong.web.suppert.collection.vo.ResultVoFactory;

/**
 * 统计服务
 *
 * @author 张成轩
 */
@Service
public class StatisticService {

	@Resource
	private StatisticDao statisticDao;

	/** 代码排序器 */
	public static Comparator<CountVo> countComparator = new Comparator<CountVo>() {

		@Override
		public int compare(CountVo o1, CountVo o2) {

			return o1.getCount() - o2.getCount();
		}
	};

	/**
	 * 获取访问路径统计
	 * 
	 * @param days 查询天数
	 * @return 返回对象
	 */
	public ResultVo<?> names(Integer days) {

		String time = getStartTime(days);
		List<CountVo> vos = statisticDao.queryNameGroup(time);
		Collections.sort(vos, countComparator.reversed());
		return ResultVoFactory.succ(vos);
	}

	/**
	 * 获取操作系统统计
	 * 
	 * @param days 查询天数
	 * @return 返回对象
	 */
	public ResultVo<?> envs(Integer days) {

		String time = getStartTime(days);
		// 查询
		List<CountVo> oss = statisticDao.queryOsGroup(time);
		List<CountVo> browsers = statisticDao.queryBrowserGroup(time);
		// 排序
		Collections.sort(oss, countComparator.reversed());
		Collections.sort(browsers, countComparator.reversed());
		// 封装返回对象
		EnvVo vo = new EnvVo();
		vo.setOss(oss);
		vo.setBrowser(browsers);
		return ResultVoFactory.succ(vo);
	}

	/**
	 * 获取起始时间
	 * 
	 * @param days 查询天数
	 * @return 起始时间
	 */
	private String getStartTime(Integer days) {

		if (days == 0) {
			return null;
		}
		Calendar c = Dates.getCurrentCDate();
		c.add(Calendar.DATE, -days + 1);
		return Dates.formatTime(c.getTime());
	}
}
